import React from 'react'
import { View, Text } from '@tarojs/components'
import { AtTextarea, AtButton, AtInputNumber } from 'taro-ui'
import Taro from '@tarojs/taro'
import './index.scss'
import { DeviceList } from '../../serverless/deviceList'
import { WeMqttApi } from '../../serverless/weMqttApi'
import { LedLogs } from '../../serverless/LedLogs'
import { formatDate } from '../../uilts/util'

export default class Index extends React.Component {

  state = {
    loading: false,
    deviceInfo: {} as DeviceList,
    ledTextLogs: [] as LedLogs[],
    ledtext: '',
    speed: 50,
    count: 0,
  }

  async componentWillMount() {
    try {
      if (!DeviceList.globalDeviceList) throw new Error('未找到设备')
      this.setState({
        deviceInfo: DeviceList.globalDeviceList,
      }, () => {
        this.getLedTextLogs()
      })
    } catch (error) {
      Taro.showModal({
        title: '加载设备信息失败',
        content: error.message,
        showCancel: false
      })
    }
  }

  handleChange(key: string, value: any) {
    this.setState({
      [key]: value
    })
  }

  /** 标识是否正在获取LED文本历史 */
  private onGetLedTextLogs = false
  async getLedTextLogs() {
    const { deviceInfo } = this.state
    try {
      if (this.onGetLedTextLogs) return
      this.onGetLedTextLogs = true
      const a = await LedLogs.GetLedTextLogs(deviceInfo.get_id(), 0)
      console.log(a);
      this.setState({
        ledTextLogs: a
      })
    } catch (error) {
      console.warn(error.message);
    }
    this.onGetLedTextLogs = false
  }


  async saveledtext(text: string) {
    const { deviceInfo } = this.state
    try {
      await LedLogs.SaveLedText(deviceInfo.get_id(), text)
      await this.getLedTextLogs()
    } catch (error) {
      console.warn(error.message);
    }
  }


  LedTextLogsView() {
    const { ledTextLogs } = this.state
    return ledTextLogs.map((x, i) => {
      return <View key={i} className='at-row ledtext-logs' onLongPress={() => {
        Taro.setClipboardData({
          data: x.ledText,
        })
      }}>
        <View className='at-col at-col-2 at-col__offset-1 center-horizontally'>
          <View className='at-icon at-icon-clock'></View>
        </View>
        <View className='at-col at-col-8 view-white-space'>
          <View className='at-row'>
            <View className='at-col at-col-12'>{x.ledText}</View>
          </View>
          <View className='at-row'>
            <View className='at-col at-col-12 time'>{formatDate(x.otherInformation?.createDate as Date).datetime2}</View>
          </View>
        </View>
      </View>
    })

  }

  viewLedtext() {
    const { ledtext, speed, deviceInfo, loading, count } = this.state
    return <View className='pad'>
      {/* 标题 */}
      <View className='at-row mag-top'>
        <View className='at-col at-col-6 at-col__offset-1 ledtext-col'>
          <Text className='at-icon at-icon-message'></Text>
          <Text className='ledtext-title'>文本轮播</Text>
        </View>
      </View>
      {/* 轮播速度 */}
      <View className='at-row mag-top speed'>
        <View className='at-col at-col-4 at-col__offset-1 '>
          <View><Text className='ledtext-title title'>轮播速度</Text></View>
          <View><Text className='ledtext-title tisp'>选值20-50，数值越小速度越快</Text></View>
        </View>
        <View className='at-col at-col-6 center-horizontally justify-content-flex-end' >
          <AtInputNumber
            type='number'
            disabledInput
            width={150}
            min={20}
            max={50}
            step={5}
            value={speed}
            onChange={this.handleChange.bind(this, "speed")}
          />
        </View>
      </View>
      {/* 轮播次数 */}
      <View className='at-row mag-top speed'>
        <View className='at-col at-col-4 at-col__offset-1 '>
          <View><Text className='ledtext-title title'>轮播次数</Text></View>
          <View><Text className='ledtext-title tisp'>选值0-99999，0则无限循环</Text></View>
        </View>
        <View className='at-col at-col-6 center-horizontally justify-content-flex-end' >
          <AtInputNumber
            type='number'
            width={150}
            min={0}
            max={99999}
            step={50}
            value={count}
            onChange={this.handleChange.bind(this, "count")}
          />
        </View>
      </View>
      {/* 输入框 */}
      <View className='at-row mag-top'>
        <View className='at-col at-col-10 at-col__offset-1'>
          <AtTextarea
            value={ledtext}
            onChange={this.handleChange.bind(this, 'ledtext')}
            maxLength={200}
            placeholder='请输入轮播的文本...'
          />
        </View>
      </View>
      {/* 发送按钮 */}
      <View className='at-row mag-top'>
        <View className='at-col at-col-10 at-col__offset-1'>
          <AtButton type='secondary' loading={loading} disabled={loading} onClick={async () => {
            try {
              if (ledtext.length == 0) return
              this.setState({ loading: true })
              const a = new WeMqttApi(deviceInfo.info.deviceId)
              const b = await a.sendText(ledtext, speed, count)
              Taro.showToast({
                title: '发送成功',
                icon: 'success',
                duration: 1600
              })
              console.log(b);
              this.saveledtext(ledtext)
            } catch (error) {
              Taro.showModal({
                title: '错误提示',
                content: error.message,
                showCancel: false
              })
            }
            this.setState({ loading: false })

          }}>发送</AtButton>
        </View>
      </View>
      {/* 历史发送 */}
      <View className='at-row mag-top'>
        <View className='at-col at-col-10 at-col__offset-1 ledtext-col'>
          <Text className='at-icon at-icon-tags'></Text>
          <Text className='ledtext-title'>历史发送</Text>
        </View>
      </View>
      {/* 列表 */}
      {this.LedTextLogsView()}
    </View>
  }

  render() {

    return (
      <View className='index guide'>
        {this.viewLedtext()}
      </View>
    )
  }
}
